<?php
class UsersCtl extends BaseCtl {
	public function UsersCtl() {
		parent::BaseCtl();
	}
	
	public function edit(){
		try {
			$frm = $this->getUsersForm();
			
			$id = $frm->getId();
			$user = $frm->getUserById($id);
			
			$form = $this->getEditUserForm();
			$form->clear();
			$form->setAdding(false);
			
			$form->setId($id);
			$form->setLogin($user->getLogin());
			$form->setName($user->getName());
			$form->setAdmin($user->isAdmin());
			$form->setConnect($user->isConnect());
			$form->setEmail($user->getEmail());
			$form->setSendEmail($user->isSendEmail());
			
			$this->redirect('edituser.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function chpass(){
		try {
			$frm = $this->getUsersForm();
			
			$id = $frm->getId();
			$user = $frm->getUserById($id);
			
			$form = $this->getChPassForm();
			$form->clear();
			
			$form->setId($id);
			$form->setName($user->getName());
			$form->setLogin($user->getLogin());
			
			$this->redirect('chpass.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function add(){
		try {
			$form = $this->getEditUserForm();
			$form->clear();
			$form->setAdding(true);
			
			$service = new Service();
			$form->setId($service->getNewId());
			
			$this->redirect('edituser.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function remove(){
		try {
			// there have to be at least on selected
			// fill out the confirm albums
			$form = $this->getUsersForm(); 
			$selected = $form->getSelected();
			
			if(count($selected) > 0){
				$service = new Service();
				
				// create array with the keys
				$arr = array();
				foreach($selected as $key => $val){
					$arr[] = $key;
				}
				
				$service->deleteUsers($arr);
				$form->deleteUsers($arr);
			}
			else {
				throw new Exception('Please select at least one user to delete');
			}
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
    public function isPostback(){
    	return 'users' == $this->getPost('pagename');
    }

    public function loadData(){
    	$arr = array();
    	$sel  = $this->getNonEmpty($this->getPost('selected'));
    	
    	foreach($sel as $current){
    		$arr[$current] = 'sel';
    	}
    	
    	$form = $this->getUsersForm();
    	$form->setSelected($arr);
    	
    	// load the id as well
    	$form->setId($this->getPost('idedit'));
    }
	
} 
?>